<template>
  <div id="">
    <van-cell
      @click="clickItem(item)"
      v-for="(item, index) in options"
      :key="index"
      icon="search"
    >
      <template #title>
        <div v-html="formatStr(item)"></div>
      </template>
    </van-cell>

    <!-- 搜索提示 -->
    <van-empty v-if="!options.length" image="search" />
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import Toast from 'vant'
export default {
  name: 'suggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      options: []
    }
  },

  // 定义方法
  methods: {
    async loadSearchSuggestion () {
      try {
        const { data: res } = await getSearchSuggestion(this.searchText)
        this.options = res.data.options
      } catch (err) {
        Toast('失败！')
      }
    },
    formatStr (str) {
      const reg = new RegExp(this.searchText, 'gi')
      return str.replace(
        reg,
        `<span style="color: red;">${this.searchText}</span>`
      )
    },
    clickItem (val) {
      this.$emit('onClickItem', val)
    }
  },

  watch: {
    searchText: {
      immediate: true, // 首次监听
      handler (newVal) {
        this.timeId && clearTimeout(this.timeId)
        this.timeId = setTimeout(() => {
          this.loadSearchSuggestion()
        }, 800)
      }
    }
  },

  beforeDestroy () {
    clearTimeout(this.timeId)
  }
}
</script>

<style scoped lang="less"></style>
